# coding:utf-8

import datetime
import time
import requests

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import text, select

BASE_MISSING_CALL_URL = 'http://127.0.0.1:5000/outbound/ccx_missing_call/{mobile}'

#BASE_MISSING_CALL_URL = 'http://opc.wanpinghui.com/outbound/ccx_missing_call/{mobile}'

DB_USER = 'cc'
DB_PWD = 'cc'
DB_HOST = '192.168.1.208:1521'
DB_NAME = 'orcl'
cc_engine = create_engine(
    'oracle+cx_oracle://%s:%s@%s/%s' % (
        DB_USER, DB_PWD, DB_HOST, DB_NAME
    )
)

cc_conn = cc_engine.connect()

sql = text("""
select
    corgani
from
    ky.t_imr_calllog
where
    NTALKSECONDS=0 and NQUEUECOUNT>0 and NTYPE=1 and tbegin>:tbegin and itenantid=202
""")

while True:
    try:
        now = datetime.datetime.now()
        delta = datetime.timedelta(seconds=60*5)
        select_result = cc_conn.execute(
            sql,
            tbegin=now-delta
        )
        mobile_list = list(select_result)
        for i in mobile_list:
            print i.corgani
            mobile = i.corgani
            missing_call_url = BASE_MISSING_CALL_URL.format(mobile=mobile)
            r = requests.post(missing_call_url)
            print(r.text)

    except Exception as e:
        print e

    print "run at: %s" % datetime.datetime.now()
    time.sleep(60*2)
